import datetime
import logging
import threading
import time

import requests

from const import MOYV_URL, DEV, MO_YV_CONF_KEYWORD
from msg_handler_impl.handler import SingleMsgHandlerBase
from util import map_list
from util import msg_send_utils, filter_list

logger = logging.getLogger()
has_send = False


def _get_sender_id(msg: dict):
    return msg['sender']["id"] if msg["type"] == "FriendMessage" else msg['sender']['group']["id"]


def _do_moyv(msg: dict, ctx, is_group=False):
    cfg = ctx.cfg
    image_url = get_image_url()
    logger.info('找到关键词，发送图片')
    msg_chain = [
        # {"type": "Plain", "text": "摸鱼日记"},
        {"type": "Image", "url": image_url}
    ]
    target_id = _get_sender_id(msg)
    if msg["type"] == "FriendMessage":
        msg_send_utils.send_friend_msg(cfg["session"], target_id, msg_chain)
    else:
        msg_send_utils.send_group_msg(cfg["session"], target_id, msg_chain)


class MoYvMsgHandler(SingleMsgHandlerBase):

    def can_handle(self, msg: dict, *args, **kwargs):
        msg_type = msg.get('type')
        return msg_type in ["FriendMessage", "GroupMessage"]

    def handle(self, msg: dict, ctx, *args, **kwargs):
        msg_chain = msg['messageChain']
        # Source类型永远为chain的第一个元素: {'type': 'Source', 'id': 26675, 'time': 1661589588}
        source_msg = msg_chain[0]
        logger.info(source_msg)
        for single_msg in msg_chain:
            single_msg_type = single_msg['type']
            if single_msg_type == 'Plain':
                content = single_msg['text']
                if content == '摸鱼':
                    _do_moyv(msg, ctx)


def get_image_url():
    headers = {
        'referer': 'http://d.jiek.top/',
    }
    try:
        image_url = requests.get(MOYV_URL, headers=headers) \
            .json()['data']['moyu_url']
        return image_url
    except Exception as e:
        logger.exception(e)
    return None


def schedule_task_handle(cfg: dict = None, keyword=MO_YV_CONF_KEYWORD, *args, **kw):
    threading.Timer(interval=25, function=schedule_task_handle, kwargs={"cfg": cfg}).start()
    global has_send
    if has_send is True:
        return
    groups = cfg['group'].split(',')
    hours = time.strftime('%H:%M', time.localtime())
    logger.info("定时任务时间: %s 当前时间: %s", cfg[keyword]['time'], hours)
    if DEV or hours == cfg[keyword]["time"]:
        if "date" in cfg[keyword]:
            splits = map_list(str.strip, cfg[keyword]["date"].split(","))
            days = [d for d in splits if "-" not in d]
            for rg in filter_list(lambda x: "-" in x, splits):
                st, ed = map_list(int, rg.split("-"))
                days.extend(list(range(st, ed)))
            ind: int = datetime.date.today().weekday()
            if ind in days:
                send_moyv_image(cfg, groups)
        else:
            send_moyv_image(cfg, groups)


def send_moyv_image(cfg, groups):
    global has_send
    image_url = get_image_url()
    for group_id in groups:
        msg_chain = [
            # {"type": "Plain", "text": "摸鱼日记"},
            {"type": "Image", "url": image_url}
        ]
        msg_send_utils.send_group_msg(cfg['session'], group_id, msg_chain)
    has_send = True
    time.sleep(50)
    has_send = False
